<template>
  <el-input
    v-model="eventSearch"
    placeholder="请输入您要查询的事故类型"
    @keyup.enter="handleSearch"
  >
    <template #append>
      <div
        class="search-btn"
        @click="handleSearch"
        :title="isSearching ? '点击清除结果' : '点击开始查询'"
      >
        {{ isSearching ? '退出查询' : '查询' }}
      </div>
    </template>
  </el-input>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useMapStore } from '@/stores/mapStore'
import { queryEventByType } from '@/api/mapgis-api/queryEventByType'
import { ElMessage } from 'element-plus'

const mapStore = useMapStore()
const eventSearch = ref('')
const isSearching = ref(false)
const source = ref(null)
const layer = ref(null)

// 监听 mapInstance 变化
watch(
  () => mapStore.mapInstance,
  (map) => {
    if (map) {
      // 进行后续地图处理

      //准备一个图层 用来放查询到的要素
      source.value = new window.ol.source.Vector({})
      layer.value = new window.ol.layer.Vector({
        source: source.value,
        style: new window.ol.style.Style({
          image: new window.ol.style.Icon({
            // 自定义图标配置
            src: '/images/定位-红色.png',
            scale: 0.6,
            anchor: [0.5, 1], // 锚点位置（底部中心）
          }),
        }),
      })
      map.addLayer(layer.value)
    }
  },
  { immediate: true },
)

// 统一处理搜索/退出逻辑
const handleSearch = async (e) => {
  try {
    // 处理点击事件和回车事件
    if (e instanceof MouseEvent || e.code === 'Enter') {
      // 退出逻辑触发：仅在按钮被点击且处于搜索状态
      if (isSearching.value && e instanceof MouseEvent) {
        source.value.clear()
        eventSearch.value = ''
        isSearching.value = false
        ElMessage.success('已清除搜索结果')
        return
      }

      // 执行查询逻辑
      const type = eventSearch.value.trim()
      if (!type) {
        ElMessage.warning('请输入事故类型')
        return
      }

      // 执行搜索逻辑触发：按钮被点击且非搜索状态 或 回车
      const features = await queryEventByType(type)
      if (features.length === 0) {
        ElMessage.warning('未找到相关事故记录')
        return
      }

      source.value.clear()
      source.value.addFeatures(features)
      isSearching.value = true
      ElMessage.success(`找到 ${features.length} 条记录`)

      const map = mapStore.mapInstance
      const view = map.getView()
      // 自动调整视图以显示全部要素
      view.fit(source.value.getExtent(), {
        padding: [50, 50, 50, 50], // 留白
      })
    }
  } catch {
    isSearching.value = false
    ElMessage.warning('未找到相关事故记录')
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
  width: 65px;
  cursor: pointer;
  transition: all 0.5s;
}
</style>
